<template>
  <div class="consultation">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h2>患者就诊</h2>
          <div>
            <el-button @click="goBack">
              <el-icon><ArrowLeft /></el-icon> 返回
            </el-button>
          </div>
        </div>
      </template>

      <div v-loading="loading">
        <!-- 预约不存在提示 -->
        <el-empty v-if="!appointmentData && !loading" description="未找到预约信息"></el-empty>

        <!-- 就诊内容 -->
        <div v-if="appointmentData" class="detail-content">
          <!-- 患者基本信息卡片 -->
          <el-card class="patient-card">
            <div class="patient-info">
              <div class="patient-avatar">
                <el-avatar :size="64" :icon="UserFilled"></el-avatar>
              </div>
              <div class="patient-details">
                <h3>
                  {{ appointmentData.patientName }}
                  <el-tag size="small" class="ml-2">
                    {{ appointmentData.patientGender === 'male' ? '男' : '女' }}
                  </el-tag>
                  <el-tag size="small" type="info" class="ml-2">
                    {{ appointmentData.patientAge || '?' }}岁
                  </el-tag>
                </h3>
                <p>
                  <span class="label">联系电话:</span> {{ appointmentData.patientPhone }}
                </p>
                <p>
                  <span class="label">就诊原因:</span> {{ appointmentData.visitReason || '未提供' }}
                </p>
                <p>
                  <span class="label">预约时间:</span> {{ formatDate(appointmentData.date) }} {{ appointmentData.timeSlot }}
                </p>
              </div>
              <div class="appointment-status">
                <el-tag :type="getStatusType(appointmentData.status)">
                  {{ getStatusText(appointmentData.status) }}
                </el-tag>
              </div>
            </div>
          </el-card>

          <!-- 就诊表单 -->
          <div class="consultation-form" v-if="appointmentData.status === '预约中'">
            <el-form
              ref="medicalFormRef"
              :model="medicalRecord"
              :rules="medicalRecordRules"
              label-width="100px"
              class="medical-form"
            >
              <h3 class="section-title">就诊记录</h3>
              
              <el-form-item label="主诉" prop="chiefComplaint">
                <el-input
                  v-model="medicalRecord.chiefComplaint"
                  type="textarea"
                  placeholder="请输入患者主诉"
                  :rows="2"
                ></el-input>
              </el-form-item>
              
              <el-form-item label="现病史" prop="presentIllness">
                <el-input
                  v-model="medicalRecord.presentIllness"
                  type="textarea"
                  placeholder="请输入现病史"
                  :rows="3"
                ></el-input>
              </el-form-item>
              
              <el-form-item label="既往史" prop="pastHistory">
                <el-input
                  v-model="medicalRecord.pastHistory"
                  type="textarea"
                  placeholder="请输入既往史"
                  :rows="2"
                ></el-input>
              </el-form-item>
              
              <!-- 体格检查 -->
              <h4 class="subsection-title">体格检查</h4>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="血压" prop="bloodPressure">
                <el-input
                      v-model="medicalRecord.bloodPressure"
                      placeholder="请输入血压 (如：120/80mmHg)"
                ></el-input>
              </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="脉搏" prop="pulse">
                    <el-input
                      v-model="medicalRecord.pulse"
                      placeholder="请输入脉搏 (如：80次/分)"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="体温" prop="temperature">
                    <el-input
                      v-model="medicalRecord.temperature"
                      placeholder="请输入体温 (如：36.5℃)"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="身高" prop="height">
                    <el-input
                      v-model="medicalRecord.height"
                      placeholder="请输入身高 (如：170cm)"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="体重" prop="weight">
                    <el-input
                      v-model="medicalRecord.weight"
                      placeholder="请输入体重 (如：65kg)"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item label="诊断结果" prop="diagnosis">
                <el-input
                  v-model="medicalRecord.diagnosis"
                  type="textarea"
                  placeholder="请输入诊断结果"
                  :rows="2"
                  required
                ></el-input>
              </el-form-item>
              
              <el-form-item label="治疗方案" prop="treatment">
                <el-input
                  v-model="medicalRecord.treatment"
                  type="textarea"
                  placeholder="请输入治疗方案"
                  :rows="3"
                ></el-input>
              </el-form-item>
              
              <div class="form-actions">
                <el-button type="primary" @click="submitMedicalRecord" :loading="submitLoading">保存就诊记录</el-button>
                <el-button type="success" @click="showPrescription">开具处方</el-button>
                <el-button type="info" @click="showMedicalOrder">开立医嘱</el-button>
                <el-button @click="completeConsultation" :loading="completeLoading">完成就诊</el-button>
              </div>
            </el-form>
          </div>
          
          <!-- 已完成就诊的提示 -->
          <div v-else-if="appointmentData.status === '已到诊'" class="completed-consultation">
            <el-result
              icon="success"
              title="就诊已完成"
              sub-title="该患者的就诊已完成，您可以查看就诊记录或返回工作站"
            >
              <template #extra>
                <el-button type="primary" @click="viewMedicalRecord">查看就诊记录</el-button>
                <el-button @click="goBack">返回工作站</el-button>
              </template>
            </el-result>
          </div>
          
          <!-- 其他状态的提示 -->
          <div v-else class="appointment-alert">
            <el-alert
              :title="getAlertTitle(appointmentData.status)"
              :type="getAlertType(appointmentData.status)"
              :description="getAlertDescription(appointmentData.status)"
              show-icon
              :closable="false"
            />
            <div class="alert-actions">
              <el-button v-if="appointmentData.status === 'pending'" type="primary" @click="confirmAppointment" :loading="confirmLoading">
                确认预约
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 处方对话框 -->
    <el-dialog
      v-model="prescriptionDialogVisible"
      title="开具处方"
      width="1000px"
      :close-on-click-modal="false"
      class="prescription-dialog"
    >
      <el-form
        ref="prescriptionFormRef"
        :model="prescription"
        :rules="prescriptionRules"
        label-width="120px"
        class="prescription-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h4 class="section-title">基本信息</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="患者姓名">
                <el-input v-model="appointmentData.patientName" disabled class="disabled-input" />
        </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="就诊日期">
                <el-input :value="formatDate(appointmentData.date)" disabled class="disabled-input" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <!-- 诊断信息 -->
        <div class="form-section">
          <h4 class="section-title">诊断信息</h4>
          <el-form-item label="诊断" prop="diagnosisText">
            <el-input 
              v-model="prescription.diagnosisText" 
              placeholder="请输入诊断结果，多个诊断请用分号(;)分隔"
              @input="updateDiagnosisList"
              class="diagnosis-input"
            />
            <div class="diagnosis-tags" v-if="prescription.diagnosis.length > 0">
              <el-tag 
                v-for="(diag, index) in prescription.diagnosis" 
                :key="index"
                closable
                @close="removeDiagnosis(index)"
                type="primary"
                class="diagnosis-tag"
              >
                {{ diag }}
              </el-tag>
            </div>
        </el-form-item>
        </div>
        
        <!-- 药品列表 -->
        <div class="form-section">
          <h4 class="section-title">药品列表</h4>
          
        <div 
            v-for="(item, index) in prescription.items"
          :key="index"
          class="medication-item"
        >
            <div class="medication-header">
              <span class="medication-number">第{{ index + 1 }}种药品</span>
              <el-button
                v-if="prescription.items.length > 1"
                type="danger"
                icon="Delete"
                circle
                size="small"
                @click="removeMedication(index)"
                class="remove-btn"
              />
            </div>
            
            <!-- 第一行：基本信息 -->
            <el-row :gutter="15" class="medication-row">
              <el-col :span="12">
              <el-form-item
                  label="药品名称"
                  :prop="`items.${index}.drugName`"
                :rules="{ required: true, message: '药品名称不能为空', trigger: 'blur' }"
              >
                  <el-select 
                    v-model="item.drugId" 
                    placeholder="请选择药品"
                    class="form-input"
                    filterable
                    clearable
                    :loading="drugsLoading"
                    @change="handleDrugChange(item.drugId, index)"
                  >
                    <el-option
                      v-for="drug in drugsList"
                      :key="drug.id"
                      :label="`${drug.name} (${drug.specification || '无规格'})`"
                      :value="drug.id"
                    >
                      <span style="float: left">{{ drug.name }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ drug.specification }}</span>
                    </el-option>
                  </el-select>
              </el-form-item>
            </el-col>
              <el-col :span="12">
              <el-form-item
                  label="规格/包装"
                  :prop="`items.${index}.specification`"
              >
                  <el-input 
                    v-model="item.specification" 
                    placeholder="如：100mg*10片/盒"
                    class="form-input"
                  />
              </el-form-item>
            </el-col>
            </el-row>
            
            <!-- 第二行：剂量信息 -->
            <el-row :gutter="15" class="medication-row">
              <el-col :span="8">
              <el-form-item
                  label="单次剂量"
                  :prop="`items.${index}.dosage`"
                :rules="{ required: true, message: '剂量不能为空', trigger: 'blur' }"
              >
                  <el-input 
                    v-model="item.dosage" 
                    placeholder="如：2片、500mg"
                    class="form-input"
                  />
              </el-form-item>
            </el-col>
              <el-col :span="8">
              <el-form-item
                  label="总数量"
                  :prop="`items.${index}.quantity`"
                  :rules="{ required: true, message: '数量不能为空', trigger: 'blur' }"
              >
                  <el-input-number 
                    v-model="item.quantity" 
                    :min="1" 
                    :max="999"
                    controls-position="right"
                    style="width: 100%"
                    class="number-input"
                  />
              </el-form-item>
            </el-col>
              <el-col :span="8">
                <el-form-item
                  label="用药天数"
                  :prop="`items.${index}.days`"
                >
                  <el-input-number 
                    v-model="item.days" 
                    :min="1" 
                    :max="30"
                    controls-position="right"
                    style="width: 100%"
                    placeholder="天数"
                    class="number-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 第三行：用法说明 -->
            <el-row :gutter="15" class="medication-row">
              <el-col :span="12">
                <el-form-item
                  label="用法频次"
                  :prop="`items.${index}.frequency`"
                  :rules="{ required: true, message: '用法频次不能为空', trigger: 'blur' }"
                >
                  <el-select 
                    v-model="item.frequency" 
                    placeholder="请选择用法频次" 
                    style="width: 100%" 
                    filterable 
                    allow-create
                    class="select-input"
                  >
                    <el-option label="每日一次" value="每日一次" />
                    <el-option label="每日两次" value="每日两次" />
                    <el-option label="每日三次" value="每日三次" />
                    <el-option label="每日四次" value="每日四次" />
                    <el-option label="每6小时一次" value="每6小时一次" />
                    <el-option label="每8小时一次" value="每8小时一次" />
                    <el-option label="每12小时一次" value="每12小时一次" />
                    <el-option label="饭前服用" value="饭前服用" />
                    <el-option label="饭后服用" value="饭后服用" />
                    <el-option label="睡前服用" value="睡前服用" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="用药说明"
                  :prop="`items.${index}.instructions`"
                >
                  <el-input 
                    v-model="item.instructions" 
                    placeholder="特殊用药说明，如：饭后服用，多饮水等"
                    class="form-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          
          <div class="add-medication">
            <el-button type="primary" plain @click="addMedication" class="add-btn">
              <el-icon><Plus /></el-icon> 添加药品
            </el-button>
          </div>
        </div>
        
        <!-- 备注信息 -->
        <div class="form-section">
          <h4 class="section-title">备注信息</h4>
          <el-form-item label="处方备注" prop="remarks">
            <el-input
              v-model="prescription.remarks"
              type="textarea"
              :rows="3"
              placeholder="处方的整体说明或注意事项"
              class="textarea-input"
            />
          </el-form-item>
        </div>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="prescriptionDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="submitPrescription" :loading="prescriptionLoading" class="submit-btn">保存处方</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 医嘱对话框 -->
    <el-dialog
      v-model="medicalOrderDialogVisible"
      title="开立医嘱"
      width="1000px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="medicalOrderFormRef"
        :model="medicalOrder"
        label-width="100px"
      >
        <el-form-item label="医嘱类型" prop="type">
          <el-select v-model="medicalOrder.type" placeholder="请选择医嘱类型" style="width: 100%">
            <el-option label="临时医嘱" value="临时医嘱" />
            <el-option label="长期医嘱" value="长期医嘱" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="medicalOrder.priority" placeholder="请选择优先级" style="width: 100%">
            <el-option label="常规" value="常规" />
            <el-option label="加急" value="加急" />
            <el-option label="紧急" value="紧急" />
          </el-select>
        </el-form-item>
        
        <h4 class="dialog-subtitle">医嘱项目</h4>
        
        <!-- 常用模板 -->
        <div class="order-templates">
          <el-text class="template-label">常用模板：</el-text>
          <el-button-group>
            <el-button 
              v-for="template in medicalOrderTemplates" 
              :key="template.name"
              size="small" 
              type="info" 
              plain
              @click="applyOrderTemplate(template)"
            >
              {{ template.name }}
            </el-button>
          </el-button-group>
        </div>
        
        <div 
          v-for="(item, index) in medicalOrder.items"
          :key="index"
          class="medical-order-item"
        >
          <el-row :gutter="15">
            <el-col :span="6">
              <el-form-item
                :label="index === 0 ? '项目类型' : ''"
                :prop="`items.${index}.type`"
              >
                <el-select v-model="item.type" placeholder="项目类型" style="width: 100%">
                  <el-option label="药品" value="药品" />
                  <el-option label="检验" value="检验" />
                  <el-option label="检查" value="检查" />
                  <el-option label="治疗" value="治疗" />
                  <el-option label="护理" value="护理" />
                  <el-option label="饮食" value="饮食" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item
                :label="index === 0 ? '医嘱内容' : ''"
                :prop="`items.${index}.content`"
              >
                <el-input 
                  v-model="item.content" 
                  type="textarea"
                  :rows="3"
                  placeholder="请详细输入医嘱内容，如：0.9%氯化钠注射液 250ml&#10;静脉滴注，速度60滴/分钟&#10;连续使用3天"
                  resize="vertical"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2" class="order-item-actions">
              <el-button
                type="danger"
                icon="Delete"
                circle
                size="small"
                @click="removeMedicalOrderItem(index)"
                v-if="medicalOrder.items.length > 1"
                style="margin-top: 32px;"
              />
            </el-col>
          </el-row>
          
          <el-row :gutter="15">
            <el-col :span="8">
              <el-form-item
                :label="index === 0 ? '频次' : ''"
                :prop="`items.${index}.frequency`"
              >
                <el-select v-model="item.frequency" placeholder="请选择或输入频次" filterable allow-create default-first-option>
                  <el-option label="每日一次" value="每日一次" />
                  <el-option label="每日两次" value="每日两次" />
                  <el-option label="每日三次" value="每日三次" />
                  <el-option label="每日四次" value="每日四次" />
                  <el-option label="每6小时一次" value="每6小时一次" />
                  <el-option label="每8小时一次" value="每8小时一次" />
                  <el-option label="每12小时一次" value="每12小时一次" />
                  <el-option label="临时使用" value="临时使用" />
                  <el-option label="立即执行" value="立即执行" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                :label="index === 0 ? '持续时间' : ''"
                :prop="`items.${index}.duration`"
              >
                <el-input v-model="item.duration" placeholder="如：3天、1周、长期" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                :label="index === 0 ? '备注' : ''"
                :prop="`items.${index}.note`"
              >
                <el-input v-model="item.note" placeholder="特殊说明" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <div class="add-order-item">
          <el-button type="primary" plain @click="addMedicalOrderItem">
            <el-icon><Plus /></el-icon> 添加医嘱项目
          </el-button>
        </div>
        
        <el-form-item label="医嘱说明" prop="note">
          <el-input
            v-model="medicalOrder.note"
            type="textarea"
            :rows="3"
            placeholder="请输入整体医嘱的说明或特殊注意事项&#10;如：注意观察患者生命体征变化&#10;如有异常立即停止用药并通知医生"
            resize="vertical"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="medicalOrderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitMedicalOrder" :loading="medicalOrderLoading">开立医嘱</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { appointmentAPI, medicalRecordAPI, prescriptionAPI, medicalOrderAPI, drugAPI } from '@/utils/api'
import { format } from 'date-fns'
import { ArrowLeft, Plus, UserFilled } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const submitLoading = ref(false)
const confirmLoading = ref(false)
const completeLoading = ref(false)
const appointmentData = ref(null)
const prescriptionDialogVisible = ref(false)
const prescriptionLoading = ref(false)
const medicalOrderDialogVisible = ref(false)
const medicalOrderLoading = ref(false)

// 药品相关数据
const drugsList = ref([])
const drugsLoading = ref(false)

// 医疗记录表单
const medicalFormRef = ref(null)
const medicalRecord = reactive({
  appointmentId: '',
  patientId: '',
  doctorId: '',
  chiefComplaint: '',
  presentIllness: '',
  pastHistory: '',
  bloodPressure: '',
  pulse: '',
  temperature: '',
  height: '',
  weight: '',
  diagnosis: '',
  treatment: '',
  advice: ''
})

// 医疗记录表单验证规则
const medicalRecordRules = {
  chiefComplaint: [
    { required: true, message: '请输入患者主诉', trigger: 'blur' }
  ],
  diagnosis: [
    { required: true, message: '请输入诊断结果', trigger: 'blur' }
  ]
}

// 处方表单
const prescriptionFormRef = ref(null)
const prescription = reactive({
  patientId: '',
  doctorId: '',
  departmentId: '',
  visitDate: '',
  diagnosisText: '', // 用于输入的文本
  diagnosis: [], // 后端需要的数组格式
  items: [
    { drugId: '', drugName: '', specification: '', dosage: '', quantity: 1, frequency: '', days: 1, instructions: '' }
  ],
  remarks: ''
})

// 处方表单验证规则
const prescriptionRules = {
  diagnosisText: [
    { required: true, message: '请输入诊断结果', trigger: 'blur' }
  ]
}

// 医嘱表单
const medicalOrderFormRef = ref(null)
const medicalOrder = reactive({
  appointmentId: '',
  patientId: '',
  doctorId: '',
  departmentId: '',
  type: '临时医嘱',
  items: [
    { type: '护理', content: '', frequency: '', duration: '', note: '' }
  ],
  priority: '常规',
  note: ''
})

// 根据路由参数获取预约ID
const appointmentId = route.params.id

// 获取预约详情
const getAppointmentDetail = async () => {
  if (!appointmentId) {
    ElMessage.error('预约ID无效')
    return
  }

  loading.value = true
  try {
    console.log('获取预约详情，ID:', appointmentId)
    const res = await appointmentAPI.getAppointment(appointmentId)
    
    console.log('原始API响应:', res)
    
    if (res.success && res.data) {
      console.log('预约详情获取成功:', res.data)
      
      // 处理预约数据
      const appointment = res.data
      
      // 标准化预约数据
      appointmentData.value = {
        id: appointment.id || appointment._id,
        appointmentId: appointment.appointmentId || appointment.id,
        patientId: appointment.patientId,
        patientName: appointment.patientName || appointment.patientInfo?.name || '未知患者',
        patientGender: appointment.patientGender || appointment.patientInfo?.gender || 'unknown',
        patientAge: appointment.patientAge || appointment.patientInfo?.age || 0,
        patientPhone: appointment.patientPhone || appointment.patientInfo?.phone || '未提供',
        doctorId: appointment.doctorId,
        doctorName: appointment.doctorName || appointment.doctorInfo?.name || '未知医生',
        departmentId: appointment.departmentId,
        departmentName: appointment.departmentName || appointment.departmentInfo?.name || '未知科室',
        date: appointment.appointmentDate || appointment.date,
        timeSlot: appointment.timeSlot || '08:00-11:30',
        period: appointment.period || '上午',
        visitReason: appointment.visitReason || appointment.reason || '常规就诊',
        status: appointment.status || 'confirmed',
        registrationType: appointment.registrationType || '普通门诊',
        registrationFee: appointment.registrationFee || 0,
        createdAt: appointment.createdAt,
        updatedAt: appointment.updatedAt
      }
      
      console.log('处理后的预约数据:', appointmentData.value)
      console.log('当前预约状态:', appointmentData.value.status)
      
      // 初始化医疗记录表单
      medicalRecord.appointmentId = appointmentData.value.id
      medicalRecord.patientId = appointmentData.value.patientId
      medicalRecord.doctorId = appointmentData.value.doctorId
      medicalRecord.departmentId = appointmentData.value.departmentId
      medicalRecord.visitDate = appointmentData.value.date
      
      // 初始化处方表单
      prescription.patientId = appointmentData.value.patientId
      prescription.doctorId = appointmentData.value.doctorId
      prescription.departmentId = appointmentData.value.departmentId
      
      // 初始化医嘱表单
      medicalOrder.appointmentId = appointmentData.value.id
      medicalOrder.patientId = appointmentData.value.patientId
      medicalOrder.doctorId = appointmentData.value.doctorId
      medicalOrder.departmentId = appointmentData.value.departmentId
      
      // 如果已经有就诊记录，尝试获取
      if (appointmentData.value.status === '已到诊') {
        await fetchMedicalRecord()
      }
    } else {
      console.error('API响应失败:', res)
      ElMessage.error('获取预约详情失败：' + (res.message || '数据不存在'))
    }
  } catch (error) {
    console.error('获取预约详情失败:', error)
    ElMessage.error('获取预约详情失败：' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 获取就诊记录
const fetchMedicalRecord = async () => {
  try {
    const res = await medicalRecordAPI.getMedicalRecordByAppointment(appointmentId)
    if (res.success && res.data) {
      Object.assign(medicalRecord, res.data)
    }
  } catch (error) {
    console.error('获取就诊记录失败:', error)
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    'pending': 'info',
    'confirmed': 'primary',
    'completed': 'success',
    'cancelled': 'danger',
    'no_show': 'warning',
    // 中文状态
    '预约中': 'info',
    '已到诊': 'warning',
    '已完成': 'success',
    '已取消': 'danger',
    '未到诊': 'warning'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'pending': '待确认',
    'confirmed': '已确认',
    'completed': '已完成',
    'cancelled': '已取消',
    'no_show': '未到诊',
    // 中文状态保持原样
    '预约中': '预约中',
    '已到诊': '已到诊',
    '已完成': '已完成',
    '已取消': '已取消',
    '未到诊': '未到诊'
  }
  return texts[status] || '未知'
}

// 获取提示标题
const getAlertTitle = (status) => {
  const titles = {
    'pending': '预约待确认',
    'cancelled': '预约已取消',
    'no_show': '患者未到诊',
    // 中文状态
    '预约中': '预约待确认',
    '已取消': '预约已取消',
    '未到诊': '患者未到诊'
  }
  return titles[status] || '状态异常'
}

// 获取提示类型
const getAlertType = (status) => {
  const types = {
    'pending': 'info',
    'cancelled': 'error',
    'no_show': 'warning',
    // 中文状态
    '预约中': 'info',
    '已取消': 'error',
    '未到诊': 'warning'
  }
  return types[status] || 'info'
}

// 获取提示描述
const getAlertDescription = (status) => {
  const descriptions = {
    'pending': '此预约尚未确认，请先确认预约后再进行就诊。',
    'cancelled': '此预约已被取消，无法进行就诊。',
    'no_show': '患者未按时到诊，无法进行就诊。',
    // 中文状态
    '预约中': '此预约尚未确认，请先确认预约后再进行就诊。',
    '已取消': '此预约已被取消，无法进行就诊。',
    '未到诊': '患者未按时到诊，无法进行就诊。'
  }
  return descriptions[status] || '当前状态无法进行就诊。'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  try {
    let date
    if (typeof dateStr === 'string') {
      if (dateStr.includes('T')) {
        date = new Date(dateStr.split('T')[0])
      } else {
        date = new Date(dateStr)
      }
    } else {
      date = new Date(dateStr)
    }
    
    if (isNaN(date.getTime())) return dateStr
    
    const weekDays = ['日', '一', '二', '三', '四', '五', '六']
    const weekDay = weekDays[date.getDay()]
    return `${format(date, 'yyyy-MM-dd')} (星期${weekDay})`
  } catch (e) {
    console.error('日期格式化错误:', e)
    return dateStr
  }
}

// 确认预约
const confirmAppointment = async () => {
  confirmLoading.value = true
  try {
    await appointmentAPI.updateAppointmentStatus(appointmentId, 'confirmed')
    ElMessage.success('预约已确认')
    getAppointmentDetail()
  } catch (error) {
    ElMessage.error('确认预约失败')
  } finally {
    confirmLoading.value = false
  }
}

// 提交就诊记录
const submitMedicalRecord = async () => {
  const valid = await medicalFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  // 验证必要的字段
  if (!medicalRecord.appointmentId || !medicalRecord.patientId || !medicalRecord.doctorId) {
    ElMessage.error('缺少必要的预约信息，请刷新页面重试')
    return
  }
  
  submitLoading.value = true
  try {
    // 先保存就诊记录（如果还没保存或有更新）
    let recordData
    
    if (!medicalRecord.id) {
      // 创建新记录时，发送完整数据
      recordData = {
        // 基本信息 - 确保都是有效的ObjectId格式
        patientId: appointmentData.value.patientId,
        visitId: appointmentId, // 使用预约ID作为就诊ID
        doctorId: appointmentData.value.doctorId,
        departmentId: appointmentData.value.departmentId,
        
        // 时间信息 - 修正为正确的ISO格式
        visitDate: new Date().toISOString(),
        
        // 必需的就诊内容字段 - 确保都有默认值
        chiefComplaint: medicalRecord.chiefComplaint || '常规就诊',
        presentIllness: medicalRecord.presentIllness || '患者无明显不适主诉',
        pastHistory: medicalRecord.pastHistory || '无特殊既往史',
        
        // 体格检查 - 使用正确的字段结构
        physicalExam: {
          bloodPressure: medicalRecord.bloodPressure || '',
          pulse: medicalRecord.pulse || '',
          temperature: medicalRecord.temperature || '',
          height: medicalRecord.height || '',
          weight: medicalRecord.weight || ''
        },
        
        // 诊断信息 - 修正为后端期望的格式，确保name字段存在
        diagnosis: medicalRecord.diagnosis && medicalRecord.diagnosis.trim() ? [
          {
            name: medicalRecord.diagnosis.trim(),
            type: '初步诊断',
            description: medicalRecord.diagnosis.trim()
          }
        ] : [
          {
            name: '常规检查',
            type: '初步诊断', 
            description: '患者进行常规检查，暂无明确诊断'
          }
        ],
        
        // 治疗方案 - 确保有默认值
        treatmentPlan: medicalRecord.treatment && medicalRecord.treatment.trim() ? 
          medicalRecord.treatment.trim() : '暂无特殊治疗方案，建议观察',
        
        // 处方列表（如果有）
        prescriptions: [],
        
        // 状态
        status: '已完成'
      }
    } else {
      // 更新已存在的记录时，只发送允许更新的字段
      recordData = {
        // 必需的就诊内容字段 - 确保都有默认值
        chiefComplaint: medicalRecord.chiefComplaint || '常规就诊',
        presentIllness: medicalRecord.presentIllness || '患者无明显不适主诉',
        pastHistory: medicalRecord.pastHistory || '无特殊既往史',
        
        // 体格检查 - 使用正确的字段结构
        physicalExam: {
          bloodPressure: medicalRecord.bloodPressure || '',
          pulse: medicalRecord.pulse || '',
          temperature: medicalRecord.temperature || '',
          height: medicalRecord.height || '',
          weight: medicalRecord.weight || ''
        },
        
        // 诊断信息 - 修正为后端期望的格式，确保name字段存在
        diagnosis: medicalRecord.diagnosis && medicalRecord.diagnosis.trim() ? [
          {
            name: medicalRecord.diagnosis.trim(),
            type: '初步诊断',
            description: medicalRecord.diagnosis.trim()
          }
        ] : [
          {
            name: '常规检查',
            type: '初步诊断', 
            description: '患者进行常规检查，暂无明确诊断'
          }
        ],
        
        // 治疗方案 - 确保有默认值
        treatmentPlan: medicalRecord.treatment && medicalRecord.treatment.trim() ? 
          medicalRecord.treatment.trim() : '暂无特殊治疗方案，建议观察',
        
        // 处方列表（如果有）
        prescriptions: [],
        
        // 状态
        status: '已完成'
      }
    }
    
    console.log('准备提交的医疗记录数据:', recordData)
    
    // 如果没有医疗记录ID，创建新记录，否则更新现有记录
    if (!medicalRecord.id) {
      console.log('创建新的医疗记录')
      const recordRes = await medicalRecordAPI.createMedicalRecord(recordData)
      if (recordRes.success) {
        medicalRecord.id = recordRes.data?.id || recordRes.data?._id
        console.log('医疗记录创建成功，ID:', medicalRecord.id)
      } else {
        throw new Error(recordRes.message || '医疗记录创建失败')
      }
    } else {
      console.log('更新现有医疗记录, ID:', medicalRecord.id)
      const updateRes = await medicalRecordAPI.updateMedicalRecord(medicalRecord.id, recordData)
      if (!updateRes.success) {
        throw new Error(updateRes.message || '医疗记录更新失败')
      }
    }
  } catch (error) {
    console.error('保存就诊记录失败:', error)
    ElMessage.error('保存就诊记录失败：' + (error.message || '网络错误'))
  } finally {
    submitLoading.value = false
  }
}

// 显示处方对话框
const showPrescription = () => {
  // 如果有诊断结果，自动填入处方中
  if (medicalRecord.diagnosis) {
    prescription.diagnosisText = medicalRecord.diagnosis
    updateDiagnosisList()
  }
  
  // 确保有最新的药品列表
  if (drugsList.value.length === 0) {
    getDrugsList()
  }
  
  prescriptionDialogVisible.value = true
}

// 显示医嘱对话框
const showMedicalOrder = () => {
  // 初始化医嘱数据
  medicalOrder.appointmentId = appointmentData.value?.id || ''
  medicalOrder.patientId = appointmentData.value?.patientId || ''
  medicalOrder.doctorId = appointmentData.value?.doctorId || ''
  medicalOrder.departmentId = appointmentData.value?.departmentId || ''
  
  medicalOrderDialogVisible.value = true
}

// 更新诊断列表
const updateDiagnosisList = () => {
  if (prescription.diagnosisText) {
    // 按分号分割诊断文本
    prescription.diagnosis = prescription.diagnosisText
      .split(';')
      .map(d => d.trim())
      .filter(d => d.length > 0)
  } else {
    prescription.diagnosis = []
  }
}

// 删除诊断
const removeDiagnosis = (index) => {
  prescription.diagnosis.splice(index, 1)
  // 更新文本框内容
  prescription.diagnosisText = prescription.diagnosis.join('; ')
}

// 添加药品
const addMedication = () => {
  prescription.items.push({ 
    drugId: '', 
    drugName: '', 
    specification: '', 
    dosage: '', 
    quantity: 1, 
    frequency: '', 
    days: 1, 
    instructions: '' 
  })
}

// 删除药品
const removeMedication = (index) => {
  prescription.items.splice(index, 1)
}

// 提交处方
const submitPrescription = async () => {
  // 确保诊断列表是最新的
  updateDiagnosisList()
  
  const valid = await prescriptionFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  // 验证诊断
  if (prescription.diagnosis.length === 0) {
    ElMessage.warning('请输入诊断结果')
    return
  }
  
  // 验证药品列表
  if (!prescription.items || prescription.items.length === 0) {
    ElMessage.warning('请至少添加一种药品')
    return
  }
  
  // 验证药品信息的完整性
  for (let i = 0; i < prescription.items.length; i++) {
    const item = prescription.items[i]
    if (!item.drugId || !item.dosage || !item.frequency || !item.quantity) {
      ElMessage.warning(`第${i + 1}种药品信息不完整，请填写完整`)
      return
    }
  }
  
  prescriptionLoading.value = true
  try {
    // 确保有医疗记录ID - 如果还没有，先创建医疗记录
    if (!medicalRecord.id) {
      console.log('处方创建前先保存医疗记录')
      await submitMedicalRecord()
      if (!medicalRecord.id) {
        throw new Error('无法获取医疗记录ID，请先保存就诊记录')
      }
    }
    
    // 准备处方数据，符合后端Schema要求
    const prescriptionData = {
      // 基本信息
      patientId: prescription.patientId,
      doctorId: prescription.doctorId,
      departmentId: prescription.departmentId,
      medicalRecordId: medicalRecord.id, // 关联医疗记录ID
      visitDate: new Date().toISOString(),
      
      // 诊断列表
      diagnosis: prescription.diagnosis,
      
      // 药品列表
      items: prescription.items.filter(item => 
        item.drugId && item.dosage && item.frequency
      ).map(item => ({
        drugId: item.drugId, // 使用真实的药品ID
        dosage: item.dosage,
        frequency: item.frequency,
        quantity: parseInt(item.quantity) || 1,
        days: parseInt(item.days) || 1,
        instructions: item.instructions || ''
      })),
      
      // 备注
      remarks: prescription.remarks || '',
      
      // 默认状态
      status: '待审核'
    }
    
    console.log('提交处方数据:', prescriptionData)
    
    const res = await prescriptionAPI.createPrescription(prescriptionData)
    if (res.success) {
      ElMessage.success('处方保存成功')
      prescriptionDialogVisible.value = false
      
      // 清空处方表单
      prescription.diagnosisText = ''
      prescription.diagnosis = []
      prescription.items = [{ 
        drugId: '', 
        drugName: '', 
        specification: '', 
        dosage: '', 
        quantity: 1, 
        frequency: '', 
        days: 1, 
        instructions: '' 
      }]
      prescription.remarks = ''
    } else {
      ElMessage.error(res.message || '保存失败')
    }
  } catch (error) {
    console.error('保存处方失败:', error)
    ElMessage.error('保存处方失败：' + (error.message || '网络错误'))
  } finally {
    prescriptionLoading.value = false
  }
}

// 医嘱模板
const medicalOrderTemplates = [
  {
    name: '静脉输液',
    type: '药品',
    content: '0.9%氯化钠注射液 250ml\n静脉滴注，速度60滴/分钟',
    frequency: '每日一次',
    duration: '3天',
    note: '注意观察输液反应'
  },
  {
    name: '口服药物',
    type: '药品',
    content: '阿莫西林胶囊 0.5g\n口服',
    frequency: '每日三次',
    duration: '7天',
    note: '饭后服用，注意过敏反应'
  },
  {
    name: '血常规检查',
    type: '检验',
    content: '血常规检查\n空腹抽血',
    frequency: '立即执行',
    duration: '',
    note: '次日晨起空腹采血'
  },
  {
    name: '护理观察',
    type: '护理',
    content: '生命体征监测\n每4小时测量体温、血压、脉搏、呼吸',
    frequency: '每日四次',
    duration: '住院期间',
    note: '如有异常立即报告医生'
  }
]

// 应用医嘱模板
const applyOrderTemplate = (template) => {
  const newItem = { ...template }
  medicalOrder.items.push(newItem)
}

// 添加医嘱项目
const addMedicalOrderItem = () => {
  medicalOrder.items.push({ 
    type: '护理', 
    content: '', 
    frequency: '', 
    duration: '', 
    note: '' 
  })
}

// 删除医嘱项目
const removeMedicalOrderItem = (index) => {
  medicalOrder.items.splice(index, 1)
}

// 提交医嘱
const submitMedicalOrder = async () => {
  // 基本验证
  if (!medicalOrder.items || medicalOrder.items.length === 0) {
    ElMessage.warning('请至少添加一项医嘱')
    return
  }
  
  // 验证医嘱项目的完整性
  for (let i = 0; i < medicalOrder.items.length; i++) {
    const item = medicalOrder.items[i]
    if (!item.content || !item.type) {
      ElMessage.warning(`第${i + 1}项医嘱信息不完整，请填写完整`)
      return
    }
  }
  
  medicalOrderLoading.value = true
  try {
    // 确保有医疗记录ID - 如果还没有，先创建医疗记录
    if (!medicalRecord.id) {
      console.log('医嘱创建前先保存医疗记录')
      await submitMedicalRecord()
      if (!medicalRecord.id) {
        throw new Error('无法获取医疗记录ID，请先保存就诊记录')
      }
    }
    
    // 准备医嘱数据，符合后端Schema要求
    const orderData = {
      // 基本信息字段
      patientId: medicalOrder.patientId,
      doctorId: medicalOrder.doctorId,
      departmentId: medicalOrder.departmentId,
      medicalRecordId: medicalRecord.id, // 关联医疗记录ID
      
      // 医嘱类型和优先级
      type: medicalOrder.type || '临时医嘱',
      priority: medicalOrder.priority || '常规',
      
      // 医嘱项目 - 确保每个项目都有必需的字段
      items: medicalOrder.items.filter(item => item.content && item.type).map(item => ({
        type: item.type,
        content: item.content,
        frequency: item.frequency || '',
        duration: item.duration || '',
        note: item.note || ''
      })),
      
      // 时间信息
      startTime: new Date().toISOString(),
      
      // 备注
      note: medicalOrder.note || '',
      
      // 默认状态
      status: '已开立'
    }
    
    console.log('提交医嘱数据:', orderData)
    
    const res = await medicalOrderAPI.createMedicalOrder(orderData)
    if (res.success) {
      ElMessage.success('医嘱开立成功')
      medicalOrderDialogVisible.value = false
      
      // 清空医嘱表单
      medicalOrder.items = [{ type: '护理', content: '', frequency: '', duration: '', note: '' }]
      medicalOrder.note = ''
      
    } else {
      ElMessage.error(res.message || '保存失败')
    }
  } catch (error) {
    console.error('开立医嘱失败:', error)
    ElMessage.error('开立医嘱失败：' + (error.message || '网络错误'))
  } finally {
    medicalOrderLoading.value = false
  }
}

// 完成就诊
const completeConsultation = () => {
  ElMessageBox.confirm('确认完成就诊吗？完成后将无法再修改。', '提示', {
    confirmButtonText: '确定',
      cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    completeLoading.value = true
    
    try {
      // 数据验证 - 确保必需字段存在
      if (!appointmentData.value?.patientId) {
        throw new Error('患者信息缺失，请刷新页面重试')
      }
      if (!appointmentData.value?.doctorId) {
        throw new Error('医生信息缺失，请刷新页面重试')
      }
      if (!appointmentData.value?.departmentId) {
        throw new Error('科室信息缺失，请刷新页面重试')
      }

      // 先保存就诊记录（如果还没保存或有更新）
      let recordData
      
      if (!medicalRecord.id) {
        // 创建新记录时，发送完整数据
        recordData = {
          // 基本信息 - 确保都是有效的ObjectId格式
          patientId: appointmentData.value.patientId,
          visitId: appointmentId, // 使用预约ID作为就诊ID
          doctorId: appointmentData.value.doctorId,
          departmentId: appointmentData.value.departmentId,
          
          // 时间信息 - 修正为正确的ISO格式
          visitDate: new Date().toISOString(),
          
          // 必需的就诊内容字段 - 确保都有默认值
          chiefComplaint: medicalRecord.chiefComplaint || '常规就诊',
          presentIllness: medicalRecord.presentIllness || '患者无明显不适主诉',
          pastHistory: medicalRecord.pastHistory || '无特殊既往史',
          
          // 体格检查 - 使用正确的字段结构
          physicalExam: {
            bloodPressure: medicalRecord.bloodPressure || '',
            pulse: medicalRecord.pulse || '',
            temperature: medicalRecord.temperature || '',
            height: medicalRecord.height || '',
            weight: medicalRecord.weight || ''
          },
          
          // 诊断信息 - 修正为后端期望的格式，确保name字段存在
          diagnosis: medicalRecord.diagnosis && medicalRecord.diagnosis.trim() ? [
            {
              name: medicalRecord.diagnosis.trim(),
              type: '初步诊断',
              description: medicalRecord.diagnosis.trim()
            }
          ] : [
            {
              name: '常规检查',
              type: '初步诊断', 
              description: '患者进行常规检查，暂无明确诊断'
            }
          ],
          
          // 治疗方案 - 确保有默认值
          treatmentPlan: medicalRecord.treatment && medicalRecord.treatment.trim() ? 
            medicalRecord.treatment.trim() : '暂无特殊治疗方案，建议观察',
          
          // 处方列表（如果有）
          prescriptions: [],
          
          // 状态
          status: '已完成'
        }
      } else {
        // 更新已存在的记录时，只发送允许更新的字段
        recordData = {
          // 必需的就诊内容字段 - 确保都有默认值
          chiefComplaint: medicalRecord.chiefComplaint || '常规就诊',
          presentIllness: medicalRecord.presentIllness || '患者无明显不适主诉',
          pastHistory: medicalRecord.pastHistory || '无特殊既往史',
          
          // 体格检查 - 使用正确的字段结构
          physicalExam: {
            bloodPressure: medicalRecord.bloodPressure || '',
            pulse: medicalRecord.pulse || '',
            temperature: medicalRecord.temperature || '',
            height: medicalRecord.height || '',
            weight: medicalRecord.weight || ''
          },
          
          // 诊断信息 - 修正为后端期望的格式，确保name字段存在
          diagnosis: medicalRecord.diagnosis && medicalRecord.diagnosis.trim() ? [
            {
              name: medicalRecord.diagnosis.trim(),
              type: '初步诊断',
              description: medicalRecord.diagnosis.trim()
            }
          ] : [
            {
              name: '常规检查',
              type: '初步诊断', 
              description: '患者进行常规检查，暂无明确诊断'
            }
          ],
          
          // 治疗方案 - 确保有默认值
          treatmentPlan: medicalRecord.treatment && medicalRecord.treatment.trim() ? 
            medicalRecord.treatment.trim() : '暂无特殊治疗方案，建议观察',
          
          // 处方列表（如果有）
          prescriptions: [],
          
          // 状态
          status: '已完成'
        }
      }
      
      console.log('准备提交的医疗记录数据:', recordData)
      
      // 如果没有医疗记录ID，创建新记录，否则更新现有记录
      if (!medicalRecord.id) {
        console.log('创建新的医疗记录')
        const recordRes = await medicalRecordAPI.createMedicalRecord(recordData)
        if (recordRes.success) {
          medicalRecord.id = recordRes.data?.id || recordRes.data?._id
          console.log('医疗记录创建成功，ID:', medicalRecord.id)
        } else {
          throw new Error(recordRes.message || '医疗记录创建失败')
        }
      } else {
        console.log('更新现有医疗记录, ID:', medicalRecord.id)
        const updateRes = await medicalRecordAPI.updateMedicalRecord(medicalRecord.id, recordData)
        if (!updateRes.success) {
          throw new Error(updateRes.message || '医疗记录更新失败')
        }
      }
      
      // 更新预约状态为已到诊
      const statusRes = await appointmentAPI.updateAppointmentStatus(appointmentId, '已到诊', {
        remarks: '就诊已完成'
      })
      if (!statusRes.success) {
        console.warn('预约状态更新失败，但医疗记录已保存')
      }
      
      ElMessage.success('就诊已完成')
      
      // 重新获取预约详情以更新状态
      await getAppointmentDetail()
      
    } catch (error) {
      console.error('完成就诊失败:', error)
      console.error('错误详情:', error.response?.data || error)
      
      // 根据错误类型提供更具体的错误信息
      let errorMessage = '完成就诊失败'
      if (error.response?.status === 400) {
        const errorData = error.response.data
        if (errorData.errors) {
          // 显示验证错误的详细信息
          const errorMessages = Object.entries(errorData.errors)
            .map(([field, messages]) => `${field}: ${Array.isArray(messages) ? messages.join(', ') : messages}`)
            .join('; ')
          errorMessage = `数据验证失败: ${errorMessages}`
        } else {
          errorMessage = errorData.message || '请求数据格式错误'
        }
      } else if (error.message) {
        errorMessage = error.message
      }
      
      ElMessage.error(errorMessage)
    } finally {
      completeLoading.value = false
    }
  }).catch(() => {})
}

// 查看就诊记录
const viewMedicalRecord = () => {
  // 查看就诊记录的逻辑，可以跳转到详情页或在当前页面显示
  ElMessage.info('暂未实现就诊记录详情页面')
}

// 返回上一页
const goBack = () => {
  router.push('/portal/doctor/workstation')
}

// 获取药品列表
const getDrugsList = async () => {
  drugsLoading.value = true
  try {
    const res = await drugAPI.getDrugs({ 
      limit: 9999, // 设置足够大的limit获取所有药品
      status: '启用' // 只获取启用状态的药品
    })
    if (res.success) {
      drugsList.value = res.data.drugs || []
      console.log(`成功获取 ${drugsList.value.length} 种药品`)
    }
  } catch (error) {
    console.error('获取药品列表失败:', error)
  } finally {
    drugsLoading.value = false
  }
}

// 药品选择变化处理
const handleDrugChange = (drugId, itemIndex) => {
  const selectedDrug = drugsList.value.find(drug => drug.id === drugId)
  if (selectedDrug) {
    // 自动填充药品信息
    prescription.items[itemIndex].drugId = selectedDrug.id
    prescription.items[itemIndex].drugName = selectedDrug.name
    prescription.items[itemIndex].specification = selectedDrug.specification || ''
    
    // 如果有默认用法信息，也可以填充
    if (selectedDrug.usage) {
      if (selectedDrug.usage.dosage) {
        prescription.items[itemIndex].dosage = selectedDrug.usage.dosage
      }
      if (selectedDrug.usage.frequency) {
        prescription.items[itemIndex].frequency = selectedDrug.usage.frequency
      }
    }
  }
}

// 页面加载时获取数据
onMounted(() => {
  getAppointmentDetail()
  getDrugsList()
})
</script>

<style scoped>
.consultation {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-content {
  padding: 20px 0;
}

.patient-card {
  margin-bottom: 20px;
}

.patient-info {
  display: flex;
  align-items: flex-start;
}

.patient-avatar {
  margin-right: 20px;
}

.patient-details {
  flex: 1;
}

.patient-details h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-weight: 500;
}

.patient-details p {
  margin: 5px 0;
  color: #666;
}

.label {
  color: #333;
  font-weight: 500;
  margin-right: 5px;
}

.ml-2 {
  margin-left: 8px;
}

.appointment-status {
  margin-left: auto;
  padding-left: 15px;
}

.section-title {
  margin: 0 0 15px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.completed-consultation {
  text-align: center;
  padding: 40px 0;
}

.appointment-alert {
  padding: 20px 0;
}

.alert-actions {
  margin-top: 20px;
  text-align: center;
}

.dialog-subtitle {
  margin: 20px 0 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

.medication-item {
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  background-color: #fafbfc;
  border: 1px solid #e4e7ed;
  position: relative;
}

.medication-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.medication-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
}

.add-medication {
  text-align: center;
  margin: 15px 0;
}

.subsection-title {
  font-size: 16px;
  margin: 20px 0 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
  color: #409eff;
}

.medical-order-item {
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  background-color: #fafbfc;
  border: 1px solid #e4e7ed;
  position: relative;
}

.medical-order-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.order-item-actions {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding-top: 8px;
}

.add-order-item {
  text-align: center;
  margin: 20px 0;
}

.add-order-item .el-button {
  padding: 12px 24px;
  font-size: 14px;
}

.order-templates {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f0f9ff;
  border-radius: 6px;
  border: 1px solid #c6f7ff;
}

.template-label {
  margin-right: 12px;
  font-weight: 500;
  color: #409eff;
}

.order-templates .el-button-group .el-button {
  margin-right: 8px;
  margin-bottom: 8px;
}

@media (max-width: 768px) {
  .patient-info {
    flex-direction: column;
    align-items: center;
  }
  
  .patient-avatar {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .patient-details {
    text-align: center;
    margin-bottom: 15px;
  }
  
  .appointment-status {
    margin-left: 0;
    padding-left: 0;
    text-align: center;
  }
}

.diagnosis-tags {
  margin-top: 8px;
}

.prescription-dialog {
  .el-dialog__body {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
  }
}

.prescription-form {
  .el-form-item__label {
    color: #333 !important;
    font-weight: 500;
    font-size: 14px;
  }
  
  .el-form-item__content {
    color: #333;
  }
}

.form-section {
  margin-bottom: 25px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.disabled-input {
  .el-input__inner {
    background-color: #f5f7fa !important;
    color: #666 !important;
    cursor: not-allowed;
  }
}

.diagnosis-input {
  .el-input__inner {
    color: #333 !important;
    font-size: 14px;
  }
}

.diagnosis-tag {
  margin-right: 8px;
  margin-bottom: 8px;
  font-size: 13px;
  padding: 8px 12px;
}

.medication-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.medication-number {
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
}

.remove-btn {
  &:hover {
    background-color: #f56c6c;
    border-color: #f56c6c;
  }
}

.medication-row {
  margin-bottom: 15px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-input {
  .el-input__inner {
    color: #333 !important;
    font-size: 14px;
    border: 1px solid #dcdfe6;
    min-width: 120px;
    padding: 8px 12px;
    
    &:focus {
      border-color: #409eff;
    }
    
    &::placeholder {
      color: #c0c4cc;
    }
  }
}

.number-input {
  min-width: 100px;
  
  .el-input__inner {
    color: #333 !important;
    font-size: 14px;
    padding: 8px 12px;
  }
  
  .el-input-number__increase,
  .el-input-number__decrease {
    color: #409eff;
    
    &:hover {
      color: #66b1ff;
    }
  }
}

.select-input {
  min-width: 140px;
  
  .el-input__inner {
    color: #333 !important;
    font-size: 14px;
    padding: 8px 12px;
  }
  
  .el-select-dropdown__item {
    color: #333;
    font-size: 14px;
    padding: 8px 20px;
  }
}

.add-btn {
  margin-top: 15px;
  padding: 12px 24px;
  font-size: 14px;
  font-weight: 500;
}

.textarea-input {
  .el-textarea__inner {
    color: #333 !important;
    font-size: 14px;
    line-height: 1.5;
    
    &::placeholder {
      color: #c0c4cc;
    }
  }
}

.dialog-footer {
  text-align: right;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}

.cancel-btn {
  margin-right: 10px;
  padding: 10px 20px;
  font-size: 14px;
}

.submit-btn {
  padding: 10px 20px;
  font-size: 14px;
  font-weight: 500;
}
</style> 